import { Button, Rate, Switch } from 'antd';
import React, { useState, createContext, useContext } from 'react'
import './Test2.less';

const Context = createContext(0)

function Test2() {
    const [count, setCount] = useState(0)
    const [grand, setGrand] = useState(true)
    const updateFunc = (num) => {
        num += 1
        if(num > 6) {
            num = 1
        }
        setCount(num)
    }
    const updateMinusFunc = (num) => {
        num -= 1
        if(num < 0) {
            num = 0
        }
        setCount(num)
    }
    // eslint-disable-next-line
    const updateCount = num => updateFunc(num)
    const updateMinusCount = num => updateMinusFunc(num)
    const updateByClick = num => setCount(num)
    const onSwitchChange = (checked) => {
        setGrand(checked)
    }
    return (
        <div className="container">
            <div className="title">是否有跨组件:</div>
            <Switch defaultChecked onChange={onSwitchChange} />
            <div className="title">父子传值:</div>
            <Child data={count} updateCount={updateCount} updateByClick={updateByClick} />
            {grand && 
                <div>
                    <div className="title">跨组件传值:</div>
                    <Context.Provider value={count}>
                        <Child2 data={count} updateMinusCount={updateMinusCount} updateByClick={updateByClick} />
                    </Context.Provider>
                </div>
            }
        </div>
    )
}

function Child(props) {
    const { data, updateCount, updateByClick } = props
    const childClick = () => updateCount(data)

    return (
        <div>
            <div>子组件：<Rate defaultValue={0} value={data} count={6} onChange={updateByClick} /></div>
            <Button type="primary" className="updateBtn" onClick={childClick}>点击+1</Button>
        </div>
    )
}

function Child2(props) {
    const { data, updateMinusCount, updateByClick } = props
    const childClick = () => updateMinusCount(data)

    return (
        <div>
            <div>子组件：<Rate defaultValue={0} value={data} count={6} onChange={updateByClick} /></div>
            <Grand />
            <Button type="primary" className="updateBtn" onClick={childClick}>点击-1</Button>
        </div>
    )
}

function Grand() {
    const count = useContext(Context)
    return (
        <div>孙组件：<Rate defaultValue={0} value={count} count={6} /> </div>
    )
}

export default Test2;